<script setup lang="ts">
import XtxSwiper from '@/components/XtxSwiper.vue'
import CustomNavbar from './components/CustomNavbar.vue'
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import XtxGuess from '@/components/XtxGuess.vue'
import PageSkeleton from '@/pages/index/components/PageSkeleton.vue'
import type { XtxGuessInstance } from '@/components/components'

const bannerList = ref<BannerItem[]>([])
const getHomeBannerData = async () => {
  const res = await getHomeBannerAPI()
  bannerList.value = res.result
}

const categoryList = ref<CategoryItem[]>([])
const getHomeCategoryData = async () => {
  const res = await getHomeCategoryAPI()
  categoryList.value = res.result
}

const hotList = ref<HotItem[]>([])
const getHomeHotData = async () => {
  const res = await getHomeHotAPI()
  hotList.value = res.result
}
// 判断是否加载完毕
const isLoading = ref(false)
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHomeHotData()])
  isLoading.value = false
})

const xtxGuess = ref<XtxGuessInstance>()
const onScrolltolower = () => {
  xtxGuess.value?.getMore()
}

const isTriggerd = ref(false)
const onRefresherrefresh = async () => {
  isTriggerd.value = true
  xtxGuess.value?.resetData()
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryData(),
    getHomeHotData(),
    xtxGuess.value?.getMore(),
  ])
  isTriggerd.value = false
}
</script>

<template>
  <CustomNavbar></CustomNavbar>
  <scroll-view
    scroll-y
    class="scroll-view"
    refresher-enabled
    @scrolltolower="onScrolltolower"
    @refresherrefresh="onRefresherrefresh"
    :refresher-triggered="isTriggerd"
  >
    <!-- 骨架图 -->
    <PageSkeleton v-if="isLoading"></PageSkeleton>
    <template v-else>
      <XtxSwiper :list="bannerList" class="banner"></XtxSwiper>
      <CategoryPanel :list="categoryList"></CategoryPanel>
      <HotPanel :list="hotList"></HotPanel>
      <XtxGuess ref="xtxGuess"></XtxGuess>
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.scroll-view {
  flex: 1;
}

.banner {
  height: 100%;
}
</style>
